<!-- 编辑弹窗 -->
<template>
  <div>
  <el-dialog
    :title="isUpdate?'修改补差申请':'添加补差申请'"
    :visible="visible"
    width="460px"
    :fullscreen="true"
    :destroy-on-close="true"
    :lock-scroll="false"
    @update:visible="updateVisible"
    @open="loadSummary">
    <el-form
      ref="form"
      class="spbceditform"
      :model="form"
      :rules="rules"
      style="margin-bottom: 10px"
      label-width="82px">
      <el-row>
        <el-col :md="4" :sm="12">
          <el-form-item label="申请日期:">
            <el-date-picker disabled v-model="form.sqrq" type="date" format='yyyy-MM-dd' value-format='yyyy-MM-dd' clearable class="ele-fluid"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :md="4" :sm="12">
          <el-form-item label="申请单号:">
            <el-input disabled v-model="form.sqdh"></el-input>
          </el-form-item>
        </el-col>
        <el-col :md="6" :sm="12">
          <el-form-item label="补差依据:" prop="bcyjList">
            <el-select
              clearable multiple collapse-tags
              :multiple-limit="1"
              @change="setBCDate"
              title="请先选择客户，将根据客户类型筛选补差依据"
              v-model="form.bcyjList"
              placeholder=""
              class="ele-fluid">
              <el-option v-for="item in bcyjList"
                         :key="item.id"
                         :label="item.bcname"
                         :value="String(item.id)"
                         :disabled="item.availableCustomer=='全部'||item.availableCustomer==form.khlx?false:true"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :md="4" :sm="12">
          <el-form-item label="开始日期:">
            <el-date-picker v-model="form.begindate" type="date" format='yyyy-MM-dd' value-format='yyyy-MM-dd' clearable class="ele-fluid"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :md="4" :sm="12">
          <el-form-item label="结束日期:">
            <el-date-picker v-model="form.enddate" type="date" format='yyyy-MM-dd' value-format='yyyy-MM-dd' clearable class="ele-fluid"></el-date-picker>
          </el-form-item>
        </el-col>       
      </el-row>
      <el-row style="margin-top:5px;">
        <el-col :md="4" :sm="12">
          <el-form-item label="客户编码:" prop="custcode">
            <el-input
              disabled
              v-model="form.custcode"
              placeholder=""/>
          </el-form-item>
        </el-col>
        <el-col :md="8" :sm="12">
          <el-form-item label="客户名称:" prop="custname">
            <el-input
              disabled
              v-model="form.custname"
              placeholder=""/>
          </el-form-item>
        </el-col>         
        <el-col :md="2" :sm="12">
          <el-button-group style="margin-left:10px;">
            <el-button size="small" type="warning" @click="selectCustomer">选择客户</el-button>
          </el-button-group>
        </el-col>
        <el-col :md="8" :sm="12">
          <el-form-item label="客户地址:">
            <el-select
              clearable multiple collapse-tags
              v-model="form.custAddr"
              class="ele-fluid">
              <el-option v-for="item in custaddrList"
                         :key="item.pkaddress"
                         :label="item.custaddress"
                         :value="item.pkaddress"
                         />
            </el-select>
          </el-form-item>
        </el-col>           
      </el-row> 
      <el-row> 
        <el-col :md="4" :sm="12">
          <el-form-item label="客户类型:" prop="khlx">
            <el-select
              disabled
              v-model="form.khlx"
              placeholder=""
              class="ele-fluid">
              <el-option label="医院" value="医院"/>
              <el-option label="商业" value="商业"/>
            </el-select>
          </el-form-item>
        </el-col>       
        <el-col :md="4" :sm="12">
          <el-form-item label="补差类型:" prop="bclx">
            <el-select
              clearable
              v-model="form.bclx"
              placeholder=""
              class="ele-fluid">
              <el-option label="票扣" value="票扣"/>
              <el-option label="折让" value="折让"/>
              <el-option label="红蓝对冲" value="红蓝对冲"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :md="12" :sm="12">
          <el-form-item label="盖章附件:" prop="uploadfile">
            <a v-bind:href="rootURL+'uploads/'+form.uploadfile" target="_blank" style="text-decoration: underline;">
              {{form.uploadfile?String(form.uploadfile).slice(String(form.uploadfile).indexOf('_')+1):''}}
            </a>
        </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.khlx=='医院'">
        <el-col :md="22" :sm="12">
          <el-form-item label="阳光平台:">
            <el-checkbox v-model="form.saleOrderSubstuted" @change="saleOrderSubstutedChanged">正票订单代填</el-checkbox>
            <el-checkbox v-model="form.reOrderSubstuted" @change="reOrderSubstutedChanged">负票订单代填</el-checkbox>
            <el-checkbox v-model="form.saleInvoicePost" @change="saleInvoicePostChanged">正票回传</el-checkbox>
            <el-checkbox v-model="form.reInvoiceUnrelated" @change="reInvoiceUnrelatedChanged">负票无关联回传</el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :md="22" :sm="12">
          <el-form-item label="备注:">
            <el-input type="textarea" style="margin-top:5px;"
              clearable
              v-model="form.bz"
              placeholder=""/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="display:none;">
        <el-col :md="22" :sm="12">
          <el-form-item label="GPO区域:">
            <el-input style="margin-top:5px;"
              clearable
              v-model="form.gpoarea"
              placeholder=""/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <ele-pro-table
      ref="tableSummary"
      :datasource="dataSummary"
      :columns="columnsSummary"
      :row-class-name="tableRowClassName"
      :toolbar="true"
      :need-page="false"
      show-summary
      :summary-method="getTotalAmount"
      @row-click="rowClick"
      :selection.sync="selectionSummary"
      highlight-current-row
      height="calc((100vh - 110px)/2)"
      max-height="calc((100vh - 110px)/2)"
      :loading="tableSummaryloading">
      <!-- 表头工具栏 -->
      <template slot="toolbar">
        <el-form v-if="false"
          :model="form"
          class="ele-form-search"
          size="small"
          :inline="true"
          @keyup.enter.native="reload"
          @submit.native.prevent>
          <el-row :gutter="10">
            <el-col :md="10">
              <el-form-item label="补差数量">
                <el-input
                  v-model="form.bcsl"
                  style="width: 120px"
                  placeholder=""
                  clearable
                  size="small"/>
              </el-form-item>
            </el-col>
            <el-col :md="10">
              <el-form-item label="补差金额">
                <el-input
                  style="width: 120px"
                  v-model="form.bcje"
                  placeholder=""
                  clearable
                  size="small"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-button
          size="small"
          type="warning"
          icon="el-icon-plus"
          class="ele-btn-icon"
          @click="openUpload"
          v-if="permission.includes('sys:bctb:add')">上传盖章附件
        </el-button>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          class="ele-btn-icon"
          @click="openSelectDetail"
          v-if="permission.includes('sys:bctb:add')">添加补差明细
        </el-button>
        <!-- <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          class="ele-btn-icon"
          @click="getPrice"
          v-if="permission.includes('sys:bctb:add')">获取销售价
        </el-button> -->
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          class="ele-btn-icon"
          @click="save"
          v-if="permission.includes('sys:bctb:add')">保存补差申请
        </el-button>
      </template>
      <template slot="bcsl" slot-scope="{row}">
        <el-input  v-model="row.balancenum" @input="calcAmout(row)"></el-input>
      </template>
      <template slot="xxsj" slot-scope="{row}">
        <el-input  v-model="row.nowsaleprice" @input="calcAmout(row)" disabled></el-input>
      </template>
      <template slot="cj" slot-scope="{row}">
        <el-input  v-model="row.diffprice" @input="calcAmout(row)" :disabled="form.khlx=='商业'?false:true"></el-input>
      </template>
      <template slot="action" slot-scope="{row}">
        <el-popconfirm
          class="ele-action"
          title="确定要删除吗？"
          @confirm="remove(row)">
          <el-link
            @click.stop
            type="danger"
            slot="reference"
            :underline="false"
            icon="el-icon-delete">删除
          </el-link>
        </el-popconfirm>
      </template>
    </ele-pro-table>
    <ele-pro-table
      ref="table"
      :datasource="dataInvoice"
      :columns="columns"
      :toolbar="false"
      :need-page="false"
      :selection.sync="selection"
      :loading="tableInvoiceloading"
      height="calc((100vh - 240px)/2)">
      <template slot="khxsl" slot-scope="{row}">
        <el-input  v-model="row.kbcsl" @input="calcAmout(row)"></el-input>
      </template>
      <template slot="hxsl" slot-scope="{row}">
        <el-input  v-model="row.quantity"></el-input>
      </template>
    </ele-pro-table>
    <div style="margin:10px;font-size: 12px;color:#1890FF;">
      <p>*补差申请填写说明：</p>
      <p>1：医院以含税单价计算补差差价，2025-02-25起商业以含税单价计算补差差价。</p>
      <p>2：医院补差类型为红蓝对冲，商业补差类型为票扣或折让，折让需有退税证明。</p>
      <p>3：仅可上传一个附件，若有多个，请使用WPS或其他工具合并成一个文件。</p>
    </div>
  </el-dialog>
  <SelectCustomer :visible.sync="showSelectCustomer" @done="setCustomer"></SelectCustomer>
    <UploadFile :visible.sync="showUpload" @done="setUploadFile"></UploadFile>
    <SelectBCDetail :visible.sync="showSelectDetail" :data="form" @done="addBCDetail"></SelectBCDetail>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import setting  from '@/config/setting'
import SelectCustomer from './select-customer'
import SelectBCDetail from './select-bcdetail'
import UploadFile from './upload';
export default {
  name: 'SpbcEdit',
  components:{SelectCustomer,UploadFile,SelectBCDetail},
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  // updated () {
  //   this.$nextTick(() => {
  //     this.$refs['tableSummary'].doLayout();
  //   });
  // },
  computed: {
    ...mapGetters(["permission"]),
  },
  mounted() {
    this.getBcyjList();
  },
  data() {
    return {
      // 表单数据
      form: {
        sqr:'',
        sqbm:'',
        sqrq:new Date(),
        custname:'',
        custcode:'',
        bcyjList:[],
        custAddr:[],
        bclx:'',
        khlx:'医院',
        bz:'',
        uploadfile:''
      },
      currentInv:{},
      bcyjList:[], //补差依据列表
      dataList:[],
      selection:[],
      dataSummary:[],
      dataInvoice:[],
      dataInvoiceList:{},
      selectionSummary:[],
      where:{},
      showSelectCustomer:false,
      showUpload:false,
      showSelectDetail:false,
      custaddrList:[],
      columns: [
        {
          columnKey: 'index',
          type: 'index',
          label: '序号',
          width: 45,
          align: 'center',
          fixed: "left"
        },
        {
          prop: 'invcode',
          label: '商品编码',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          prop: 'invname',
          label: '商品名称',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'left'
        },
        {
          prop: 'dbilldate',
          label: '原销售日期',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'center'
        },
        {
          prop: 'vgoldtaxcode',
          label: '原发票',
          showOverflowTooltip: true,
          minWidth: 150,
          align: 'left'
        },
        {
          prop: 'vlotno',
          label: '批号',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'left'
        },
        {
          prop: 'nastnum',
          label: '原销售数量',
          showOverflowTooltip: true,
          minWidth: 90,
          align: 'center'
        },
        {
          prop: 'balancenum',
          label: '可核销数量',
          showOverflowTooltip: true,
          minWidth: 90,
          align: 'center',
        },
        {
          prop: 'quantity',
          label: '核销数量',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center',
          slot:'hxsl'
        },
        {
          prop: 'nqtorigtaxprice',
          label: '原销售价(含税)',
          showOverflowTooltip: true,
          minWidth: 110,
          align: 'center'
        },
        {
          prop: 'norigtaxmny',
          label: '含税金额',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          prop: 'norigmny',
          label: '无税金额',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          prop: 'ywy',
          label: '业务员',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          prop: 'custaddress',
          label: '客户地址',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'left'
        }
      ],
      columnsSummary: [
        {
          columnKey: 'index',
          type: 'index',
          label: '序号',
          width: 45,
          align: 'center',
          fixed: "left"
        },
        {
          prop: 'invcode',
          label: '商品编码',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'left'
        },
        {
          prop: 'invname',
          label: '商品名称',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'left'
        },
        {
          prop: 'gg',
          label: '规格',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'left'
        },
        {
          prop: 'materialunit',
          label: '单位',
          showOverflowTooltip: true,
          minWidth: 50,
          align: 'center'
        },
        {
          prop: 'manufacturer',
          label: '生产厂家',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'left'
        },
        {
          prop: 'vlotno',
          label: '批号',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'left'
        },
        {
          prop: 'nqtorigtaxprice',
          label: '含税单价',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          prop: 'nqtorigprice',
          label: '无税单价',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        // {
        //   prop: 'norigtaxmny',
        //   label: '含税金额',
        //   showOverflowTooltip: true,
        //   minWidth: 100,
        //   align: 'center'
        // },
        // {
        //   prop: 'norigmny',
        //   label: '无税金额',
        //   showOverflowTooltip: true,
        //   minWidth: 100,
        //   align: 'center'
        // },
        {
          prop: 'nastnum',
          label: '原销售数量',
          showOverflowTooltip: true,
          minWidth: 90,
          align: 'center'
        },
        {
          prop: 'remainnum',
          label: '可补差数量',
          showOverflowTooltip: true,
          minWidth: 90,
          align: 'center'
        },
        {
          prop: 'balancenum',
          label: '补差数量',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center',
          slot:'bcsl'
        },
        {
          prop: 'nowsaleprice',
          label: '现销售价',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center',
          slot:'xxsj'
        },
        {
          prop: 'diffprice',
          label: '差价',
          showOverflowTooltip: true,
          minWidth: 70,
          align: 'center',
          slot:'cj'

        },
        {
          prop: 'balanceamount',
          label: '补差金额(含税)',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          prop: 'cgy',
          label: '采购员',
          showOverflowTooltip: true,
          minWidth: 80,
          align: 'center'
        },
        {
          columnKey: 'action',
          label: '操作',
          width: 100,
          align: 'center',
          resizable: false,
          slot: 'action',
          fixed: "right"
        }
      ],
      // 表单验证规则
      rules: {
        bcyjList: [
          {required: true, message: '请选择补差依据', trigger: 'blur'}
        ],
        custname: [
          {required: true, message: '请选择客户', trigger: 'blur'}
        ],
        custcode: [
          {required: true, message: '请选择客户', trigger: 'blur'}
        ],
        khlx: [
          {required: true, message: '请选择客户', trigger: 'blur'}
        ],
        bclx: [
          {required: true, message: '请选择补差类型', trigger: 'blur'}
        ],
        uploadfile: [
          {required: true, message: '请上传盖章附件', trigger: 'blur'}
        ]

      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      bcyjBegindate:{},
      tableSummaryloading: false,
      tableInvoiceloading: false,
      baseURL: setting.baseURL,
      rootURL: setting.rootURL
    };
  },
  watch: {
    data() {
      if (this.data) {
        this.form = Object.assign({}, this.data);
        this.isUpdate = true;
      } else {
        this.form = {};
        this.form.sqrq = new Date();
        this.$set(this.form,'saleOrderSubstuted',false);
        this.$set(this.form,'reOrderSubstuted',false);
        this.$set(this.form,'saleInvoicePost',false);
        this.$set(this.form,'reInvoiceUnrelated',true);
        this.isUpdate = false;
      }
    }
  },
  methods: {
    loadSummary(){
      if (this.data) {
        this.tableSummaryloading = true;
        this.tableInvoiceloading = true;
        this.form = Object.assign({}, this.data);
        let param = {
          pid:this.data.id,
          custcode:this.form.custcode,
          bcyjList:this.form.bcyjList,
          begindate:this.form.begindate,
          enddate:this.form.enddate,
          custaddrList:this.form.custAddr
        };
        this.dataSummary = [];
        this.dataInvoice = [];
        this.dataInvoiceList={};
        this.currentInv = {};
        this.getCustAddrList(this.form.custcode);
        this.$http.post('/spbc/detaillist',param).then(res=>{
          if(res.status==200)
          {
            this.dataSummary = res.data.data;
            if(this.dataSummary.length>0)
            {
              this.rowClick(this.dataSummary[0]);
              this.$nextTick(() => {
                this.$refs['tableSummary'].doLayout();
              });
            }
            this.tableInvoiceloading = false;
            this.tableSummaryloading = false;
          }
        });
        
      }
      else{
        this.form={};
        this.form.sqrq = new Date();
        this.$set(this.form,'saleOrderSubstuted',false);
        this.$set(this.form,'reOrderSubstuted',false);
        this.$set(this.form,'saleInvoicePost',false);
        this.$set(this.form,'reInvoiceUnrelated',true);
        this.dataSummary=[];
        this.dataInvoice=[];
        this.currentInv={};
        this.dataInvoiceList={};
      }
      
    },
    async getBcyjList(){
      var res = await this.$http.get('/spbcinvset/getValidatedList?page=1&limit=1000');
      //console.log(res);
      if(res.status==200)
      {
        this.bcyjList = res.data.data.records;
        this.bcyjBegindate = {};
        for(let i=0; i< res.data.data.records.length; i++){
          this.bcyjBegindate[res.data.data.records[i].id] = res.data.data.records[i].begindate;
        }
      }

    },
    openUpload(){
      this.showUpload = true;
    },
    openSelectDetail(){
      if(!this.form.custcode)
      {
        this.$message.info('请选择客户')
        return;
      }
      if(this.form.bcyjList.length==0){
        this.$message.info('请选择补差依据')
        return;
      }
      this.showSelectDetail = true;
    },
    async rowClick(row){
      this.tableInvoiceloading = true;
      if(this.currentInv.id != null){
        this.dataInvoiceList[this.currentInv.id] = JSON.parse(JSON.stringify(this.dataInvoice));
      }
      this.currentInv = row;
      this.dataInvoice=[];
      if(row.id in this.dataInvoiceList){
        this.dataInvoice = this.dataInvoiceList[row.id];
        this.tableInvoiceloading = false;
      }else{
        let param = {}
        
        param = {
          custcode:this.form.custcode,
          invcode:row.invcode,
          vlotno:row.vlotno,
          nqtorigtaxprice:row.nqtorigtaxprice,
          pid:this.data==null?0:this.data.id,
          did:row.id.length==36?0:row.id,
          begindate:this.form.begindate,
          enddate:this.form.enddate,
          custaddrList:this.form.custAddr
        }
        
        var res = await this.$http.post('/spbc/invoicelist/',param);
        //console.log(res);    
        if(res.status==200)
        {
          this.dataInvoice = res.data.data; 
          for(let v of this.dataInvoice)
          {
            v.pid = this.data?this.data.id:0;
            v.did = row.id;
          }
          this.dataInvoiceList[row.id] = JSON.parse(JSON.stringify(this.dataInvoice));
          this.dataInvoice = this.dataInvoiceList[row.id];
          this.tableInvoiceloading = false;
        }
      }
    },
    //客户类型变化后，自动重新计算补差金额
    recalcAmount()
    {
      for(let row of this.dataSummary)
      {
        if(row.isBalance==='是') {
          this.calcAmout(row);
        }
      }
    },
    calcAmout(row){
      //补差差价：原开票价（医院含税，商务无税）- 新开票价 //2025-02-25 商业差价计算改为以含税价格计算
      if(row.balancenum && row.nowsaleprice) {

        if (this.form.khlx == '医院') {
          //let hsdj = row.nqtorigtaxprice;
          let cj = Number(row.nqtorigtaxprice) - Number(row.nowsaleprice);
          row.diffprice = parseFloat(cj.toFixed(8));
          row.balanceamount = parseFloat((Number(row.balancenum) * row.diffprice)).toFixed(8);  
        } else {
          //let wsdj = row.nqtorigprice;
          if (row.diffprice == null || row.diffprice == "") {
            let cj = Number(row.nqtorigtaxprice) - Number(row.nowsaleprice);
            row.diffprice = parseFloat(cj.toFixed(8));
          }
          row.balanceamount = parseFloat((Number(row.balancenum) * row.diffprice)).toFixed(8);
        }
      }
      else
      {
        row.diffprice="";
        row.balanceamount="";
      }     
    },
    setUploadFile(filename)
    {
      this.$set(this.form,'uploadfile',filename);
    },
    setCustomer(custcode,custname,custtype,gpoarea)
    {
      this.$set(this.form,'custcode',custcode);
      this.$set(this.form,'custname',custname);
      this.$set(this.form,'khlx',custtype);
      this.$set(this.form,'gpoarea',gpoarea);
      if(this.form.khlx=='医院'){
        this.$set(this.form,'bclx','红蓝对冲');
      }else{
        this.$set(this.form,'bclx','票扣');
      }
      this.getCustAddrList(custcode);
      this.dataSummary = [];
      this.dataInvoice = [];
      this.dataInvoiceList={};
      this.currentInv = {};
      this.$set(this.form,'bcyjList',[]);
    },
    getCustAddrList(custcode){
      this.$http.get('/spbc/getCustAddrList?custcode='+custcode).then(res => {
          if (res.data.code === 0) {
            this.custaddrList = res.data.data;
          }
      });
    },
    selectCustomer(){
      this.showSelectCustomer = true;
    },
    reset()
    {},
    getPrice(){

    },
    /* 保存编辑 */
    save() {
      
      //检查发票明细中的核销总数和补差数量是否一致
      var errMsg = "";
      for(let d of this.dataSummary){
        if(!d.balancenum){
          errMsg+="请填写第"+(d.index+1).toString()+"行补差数量；";
        }
      }
      for(const key in this.dataInvoiceList)
      {
        if(this.dataInvoiceList[key].length===0){continue;}
        var totalQuantity = 0;
        var amount = 0;
        var tempSummary = {};
        for(let d of this.dataSummary){
          if(d.id == key){
            tempSummary = JSON.parse(JSON.stringify(d));
            break;
          }         
        }
        for(let v of this.dataInvoiceList[key]){
          if(v.invcode != tempSummary.invcode || v.vlotno != tempSummary.vlotno){
            errMsg+="第"+(tempSummary.index+1).toString()+"行明细关联发票有误，请删除后重新添加；";
            break;
          }
          if(Number(v.quantity)>Number(v.balancenum))
          {
            errMsg="核销数量不能超过可核销数量；";
          }
          totalQuantity+=Number(v.quantity);
          v.origsaleprice = this.form.khlx=='医院'?tempSummary.nqtorigtaxprice:tempSummary.nqtorigtaxprice;
          v.diffprice = tempSummary.diffprice;
          v.nowsaleprice = tempSummary.nowsaleprice;
          amount = Number(v.diffprice)*Number(v.quantity);
          v.balanceamount = parseFloat(amount.toFixed(8));
        }
        //console.log(totalQuantity);
        //console.log(tempSummary.balancenum);
        if(tempSummary.balancenum){
          if(totalQuantity!= tempSummary.balancenum){
            errMsg+="第"+(tempSummary.index+1).toString()+"行发票核销的补差数量与申请的补差数量不一致；";
          }
        }
      }
      if(errMsg!="")
      {
        this.$message.info(errMsg);
        return;
      }
      
      this.$refs['form'].validate((valid) => {
        if (valid) {
          //this.loading = true;
          const loading = this.$loading({lock: true});
          let param = {
            headInfo:this.form,
            spbcSummaries:this.dataSummary,
            spbcInvoices:this.dataInvoiceList
          };
          this.$http[this.isUpdate ? 'put' : 'post'](this.isUpdate ? '/spbc/update' : '/spbc/create', param).then(res => {
            loading.close();
            //this.loading = false;
            if (res.data.code === 0) {
              this.$message.success(res.data.msg);
              this.updateVisible(false);
              this.$parent.reload();
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            loading.close();
            //this.loading = false;
            if(e.message.startsWith('Cannot set properties')){
              this.updateVisible(false);
              this.$parent.reload();
            }else{
              this.$message.error(e.message);
            }
          });
        } else {
          return false;
        }
      });
    },
    remove(row)
    {
      this.dataSummary.splice(row.index,1);
      this.dataInvoice=[];
      delete this.dataInvoiceList[row.id];
    },
    /* 更新visible */
    updateVisible(value) {
      this.$emit('update:visible', value);
    },
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex;
    },
    getTotalAmount(param) {
        const { columns, data } = param;
        const sums = {};
        columns.forEach((column, index) => { 
            if (index === 0) {
                sums[index] = '合计';
                return;
            }          
            const values = data.map(item => Number(item[column.property]));
            if (column.label == "补差金额(含税)") {
              if (!values.every(value => isNaN(value))) {
                  sums[index] = values.reduce((prev, curr) => {
                      const value = Number(curr);
                      if (!isNaN(value)) {
                          return parseFloat((prev + curr).toFixed(8));
                      } else {
                          return parseFloat(prev.toFixed(8));
                      }
                  }, 0);
                  
              } 
            }
        });
        return sums;
    },
    setBCDate(item){
      if(item.length>0){
        var enddate = new Date(this.bcyjBegindate[item[0]]);
      }
      for(let i=1; i<item.length; i++){
        if((new Date(this.bcyjBegindate[item[i]])) - enddate <0 ){
          enddate = new Date(this.bcyjBegindate[item[i]]);
        }
      }
      if(item.length>0){
        var startdate = new Date(enddate);
        startdate.setMonth(startdate.getMonth()-10);
        enddate.setDate(enddate.getDate()-1);
        this.$set(this.form,'begindate',startdate);
        this.$set(this.form,'enddate',enddate);
      }
      this.dataSummary = [];
      this.dataInvoice = [];
      this.dataInvoiceList={};
      this.currentInv = {};

    },
    addBCDetail(row){
      for(let s of this.dataSummary){
        if(row.invcode == s.invcode && row.vlotno == s.vlotno && row.nqtorigtaxprice == s.nqtorigtaxprice){
          return
        }
      }
      this.dataSummary.push(row);
      this.$nextTick(() => {
        this.$refs['tableSummary'].doLayout();
      });
    },
    saleOrderSubstutedChanged(){
      if(this.form.saleOrderSubstuted == true){
        this.$set(this.form,'saleInvoicePost',true);
      }
    },
    reOrderSubstutedChanged(){
      if(this.form.reOrderSubstuted == true){
        this.$set(this.form,'reInvoiceUnrelated',false);
      }
    },
    saleInvoicePostChanged(){
      if(this.form.saleInvoicePost == false){
        this.$set(this.form,'saleOrderSubstuted',false);
      }
    },
    reInvoiceUnrelatedChanged(){
      if(this.form.reInvoiceUnrelated == true){
        this.$set(this.form,'reOrderSubstuted',false);
      }
    }
  }
}
</script>

<style scoped>
::v-deep .el-dialog__body {
  padding-top: 5px;
  padding-bottom: 5px;
}
.el-row {
  margin-bottom: -15px;
}
.el-row1 {
  margin-bottom: 5px;
  margin-top: 1px;
  display: flex;
  flex-wrap: wrap
}
.spbceditform::v-deep .el-form-item__error {
  margin-top:-23px;
  left:15px;
  padding-top:0;
}
</style>
